package cn.topkinson.lagou.s3m4.code.service;

import cn.topkinson.base.api.code.CodeRemoteClient;
import cn.topkinson.base.api.email.EmailRemoteClient;
import com.alibaba.dubbo.config.annotation.Service;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @Author huangzihao
 * @Date 2020/9/9 20:11
 */
@Service
public class CodeService implements CodeRemoteClient {

    @Reference
    private EmailRemoteClient emailRemoteClient;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private final static String REGISTER_CODE_KEY = "register:code:";

    @Override
    public Boolean create(String email) {
        String code = ""+new Random().nextInt(999999);
        redisTemplate.opsForValue().set(REGISTER_CODE_KEY+email,code,10, TimeUnit.MINUTES);
        return emailRemoteClient.email(email,code);
    }

    //0正确1错误2超时
    @Override
    public Integer validate(String email, String code) {
        String key = REGISTER_CODE_KEY + email;
        Boolean aBoolean = redisTemplate.hasKey(key);
        if(aBoolean!=null && aBoolean){
            String redis_key = redisTemplate.opsForValue().get(REGISTER_CODE_KEY + email);
            if (code.equals(redis_key)) {
                return 0;
            }else{
                return 1;
            }
        }else{
            return 2;
        }
    }
}
